package cn.com.lms.business.livecourse.service;

import cn.com.lms.business.livecourse.persistence.entity.CourseChatRoom;
import cn.com.lms.business.livecourse.persistence.repository.CourseChatRoomRepository;
import com.bnzj.core.persistence.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * CourseChatRoomService
 *
 * @author barry
 * @date 2020/3/21
 **/
@Service
public class CourseChatRoomService extends BaseService<CourseChatRoomRepository, CourseChatRoom, Integer> {

    @Autowired
    private TencentImService tencentImService;

    /**
     * 定时清除无用直播课程的聊天室
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public void destroyUnlessChatRooms() {
        System.out.println("destroyUnlessChatRooms current time :" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        // 查找已过期无用房间
        Date date = new Date();
//        System.out.println("date = " + date);
        List<CourseChatRoom> unlessRooms = this.repository.unlessCourseChatRooms(date);
        // 解散已无用的房间
        if (null != unlessRooms || unlessRooms.size() > 0) {
            for (CourseChatRoom room : unlessRooms) {
                boolean destroyRe = tencentImService.destroyLiveCourseGroup(room.getTimGroupId());
                if (destroyRe) {
                    this.repository.deleteById(room.getId());
                }
            }
        }
    }

    /**
     * 删除对应课程的聊天室房间
     *
     * @param courseId 课程id
     */
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public void destroyCourseChatRoom(long courseId) throws Exception {
        if (0 >= courseId) {
            return;
        }

        boolean destroyRe = false;
        try {
            CourseChatRoom courseChatRoom = this.repository.courseChatRoom(courseId);
            if (null != courseChatRoom) {
                destroyRe = tencentImService.destroyLiveCourseGroup(courseChatRoom.getTimGroupId());
                if (destroyRe) {
                    this.repository.deleteById(courseChatRoom.getId());
                }
            } else {
                destroyRe = true;   // 无聊天室待释放
            }
        } catch (Exception e) {
//            e.printStackTrace();
            throw new Exception("解散对应课程的聊天室房间失败");
        }

        if (!destroyRe) {
            throw new Exception("解散对应课程的聊天室房间失败");
        }
    }

    /**
     * 获取可用的聊天室
     *
     * @return
     */
    @Transactional
    public CourseChatRoom getCourseChatRoom(long courseId, Date liveStartTime) {
        // 添加新房间
        Date date = new Date();
        String timGroupName = "course_chat_room_" + courseId;
        String timGroupId = "course_chat_group_" + courseId;
        boolean result = tencentImService.createLiveCourseGroup(timGroupName, timGroupId);
        if (!result) {
            return null;
        }
        // 添加直播课程聊天室记录
        CourseChatRoom chatRoom = new CourseChatRoom();
        chatRoom.setTimGroupName(timGroupName);
        chatRoom.setTimGroupId(timGroupId);
        chatRoom.setTimGroupType(1);
        chatRoom.setCourseInfoId((int) courseId);
        chatRoom.setCourseExpireTime(new Date(liveStartTime.getTime() + 12 * 3600 * 1000));
        chatRoom.setCreateTime(date);
        chatRoom = this.save(chatRoom);
        System.out.println(chatRoom.toString());
        return chatRoom;
    }

    /**
     * 释放对应课程的房间占用
     *
     * @param courseId
     */
    public void releaseRoom(long courseId) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis() + 30 * 60 * 1000);    // 多保留房间30分钟
        this.repository.releaseRoom(courseId, date);
    }

    /**
     * 释放对应课程的房间占用
     *
     * @param courseId
     */
    @org.springframework.transaction.annotation.Transactional
    public void updateRoomExpireTime(long courseId, Date liveStartTime) {
        if (0 >= courseId || null == liveStartTime) {
            return;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(liveStartTime.getTime() + 12 * 3600 * 1000);
        this.repository.updateRoomExpireTime(courseId, date);
    }
}
